/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.streamline.services.db;

import com.vii.streamline.services.error.StreamLineException;
import com.vii.streamline.services.reflection.ReflectionServices;
import com.vii.streamline.structures.collections.InnerList;
import com.vii.streamline.structures.collections.InnerMap;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.dbcp.managed.DataSourceXAConnectionFactory;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;

import javax.sql.XADataSource;
import javax.transaction.TransactionManager;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

import static com.vii.streamline.services.reflection.ReflectionServices.getMethod;
import static com.vii.streamline.services.reflection.ReflectionServices.invokeMethod;

/**
 * Helper class defining database-related methods.
 */
public class DBServices {

    /** The supported database vendors map. */
    public static HashMap<String, Map> DB_VENDORS;

    static{
        DB_VENDORS = new InnerMap<String, Map>(
                new InnerList<String>( "PostgreSQL", "Oracle", "MySQL" ),
                new InnerList<InnerMap>(
                    new InnerMap<String, String>(
                            new InnerList<String>( "connectionURL", "dsdriver", "xadriver", "defaultPort" ),
                            new InnerList<String>( "jdbc:postgresql://address:port/database", "org.postgresql.Driver", "org.postgresql.xa.PGXADataSource", "5432" )
                    ),
                    new InnerMap<String, String>(
                            new InnerList<String>( "connectionURL", "dsdriver", "xadriver", "defaultPort" ),
                            new InnerList<String>( "jdbc:oracle:thin:@address:port:database", "oracle.jdbc.driver.OracleDriver", "oracle.jdbc.xa.OracleXADataSource", "1521" )
                    ),
                    new InnerMap<String, String>(
                            new InnerList<String>( "connectionURL", "dsdriver", "xadriver", "defaultPort" ),
                            new InnerList<String>( "jdbc:mysql://address:port/database", "com.mysql.jdbc.Driver", "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource", "3306" )
                    )
                )
        );
    }

    public static void initVendors( HashMap<String, Map> vendors ){
        DB_VENDORS = vendors;
    }

    public static void close( Statement... ss ){
        for (Statement s : ss) {
            if( s != null ) {
                try {
                    s.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void close( ResultSet... rs ){
        for (ResultSet r : rs) {
            if( r != null ) {
                try {
                    r.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Gets the data source from a connection. It may be simple, or XA capable. Will use the classloader of this class and the built-in TransactionManager: {@link SimpleTransactionManager}
     * @param <C> the generic type of the parameter which must be a subclass of {@link DBMediator}.
     * @param dm The {@link DBMediator} or it's subclass from which to request the {@link javax.sql.DataSource}.
     * @return The {@link javax.sql.DataSource} of the {@link DBMediator}.
     * @throws StreamLineException On any error during the request of the {@link javax.sql.DataSource}.
     */
    public static <C extends DBMediator> javax.sql.DataSource getDataSource(
            C dm
    ) throws StreamLineException {
        return  getDataSource(
                dm,
                DBServices.class.getClassLoader(),
                SimpleTransactionManager.class
        );
    }

    /**
     * Gets the data source from a connection. It may be simple, or XA capable.
     * @param <C> the generic type of the parameter which must be a subclass of {@link DBMediator}.
     * @param <T> the generic type of the parameter which must be a subclass of {@link TransactionManager}.
     * @param dm The {@link DBMediator} or it's subclass from which to request the {@link javax.sql.DataSource}.
     * @param loader The {@link ClassLoader} instance to be used for load the JDBC driver class.
     * @param transactionManagerType Class reference of an implementation of class {@link TransactionManager}.
     * @return The {@link javax.sql.DataSource} of the {@link DBMediator}.
     * @throws StreamLineException On any error during the request of the {@link javax.sql.DataSource}.
     */
    public static <C extends DBMediator, T extends TransactionManager> javax.sql.DataSource getDataSource(
            C dm, ClassLoader loader, Class<T> transactionManagerType
    ) throws StreamLineException {
        return  dm.isXaCapable()
                ? getXADataSource( dm, loader, transactionManagerType )
                : getDSDataSource( dm, loader, transactionManagerType );
    }

    /**
     * Gets the simple data source.
     * @param <C> the generic type of the parameter which must be a subclass of {@link DBMediator}.
     * @param dm The {@link DBMediator} or it's subclass from which to request the {@link javax.sql.DataSource}.
     * @return The simple {@link javax.sql.DataSource} of the {@link DBMediator}.
     * @throws StreamLineException On any error during the request of the {@link javax.sql.DataSource}.
     */
    public static <C extends DBMediator, T extends TransactionManager> javax.sql.DataSource getDSDataSource(
            C dm, ClassLoader loader, Class<T> transactionManagerType
    ) throws StreamLineException {
        String vendor = dm.getVendor();

        String userName = dm.getUsername();
        String password = dm.getPassword();
        String database = dm.getDatabase();

        String address = dm.getAddress() == null ? "localhost" : dm.getAddress();
        String port = dm.getPort() == null ? DB_VENDORS.get( vendor ).get("defaultPort").toString() : dm.getPort();

        String connectionURI = DB_VENDORS.get( vendor ).get("connectionURL").toString()
                .replace( "address", address )
                .replace( "port", port )
                .replace( "database", database );

        try {
            Class c = loader.loadClass(
                    DB_VENDORS.get(vendor).get("dsdriver").toString()
            );
            DriverManager.registerDriver(new DriverShim((Driver) c.newInstance()));
        } catch (Exception e) {
            throw new StreamLineException( "Cannot load driver for:: " + dm, e );
        }

        ObjectPool connectionPool = new GenericObjectPool(null);

        DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                connectionURI, userName, password
        );

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                connectionFactory,connectionPool,null,null,false,true
        );

        PoolingDataSource dataSource = new PoolingDataSource(connectionPool);

        dataSource.setAccessToUnderlyingConnectionAllowed( true );

        dm.setDs( dataSource );

        return dataSource;
    }

    /**
     * Gets the SA data source.
     * @param <C> the generic type of the parameter which must be a subclass of {@link DBMediator}.
     * @param dm The {@link DBMediator} or it's subclass from which to request the {@link javax.sql.DataSource}.
     * @return The simple {@link javax.sql.DataSource} of the {@link DBMediator}.
     * @throws StreamLineException On any error during the request of the {@link javax.sql.DataSource}.
     */
    public static <C extends DBMediator, T extends TransactionManager> javax.sql.DataSource getXADataSource(
            C dm, ClassLoader loader, Class<T> transactionManagerType
    ) throws StreamLineException {
        String vendor = dm.getVendor();

        String userName = dm.getUsername();
        String password = dm.getPassword();
        String database = dm.getDatabase();

        String address = dm.getAddress() == null ? "localhost" : dm.getAddress();
        String port = dm.getPort() == null ? DB_VENDORS.get( vendor ).get("defaultPort").toString() : dm.getPort();

        XADataSource xds = null;
        try {
            xds = (XADataSource)loader.loadClass(
                DB_VENDORS.get( vendor ).get("xadriver").toString()
            ).newInstance();

            Class c = loader.loadClass(
                DB_VENDORS.get( vendor ).get("dsdriver").toString()
            );
            DriverManager.registerDriver(new DriverShim( (Driver) c.newInstance()));
        } catch (Exception e) {
            throw new StreamLineException( "Cannot load driver for:: " + dm, e );
        }

        try {
            invokeMethod(
                    getMethod(dm.getClass(), "setUser", String.class), dm, userName
            );
            invokeMethod(
                    getMethod(dm.getClass(), "setPassword", String.class), dm, password
            );
            invokeMethod(
                getMethod( dm.getClass(), "setServerName", String.class ), dm, address
            );
            invokeMethod(
                getMethod( dm.getClass(), "setPortNumber", int.class ), dm, Integer.parseInt( port )
            );
            invokeMethod(
                getMethod( dm.getClass(), "setDatabaseName", String.class ), dm, database
            );
        } catch (Exception e) {
            throw new StreamLineException( "Error while setting fields for:: " + dm );
        }

        ObjectPool connector = new GenericObjectPool(null);
        TransactionManager tm = null;
        try {
            tm = ReflectionServices.newInstance(transactionManagerType);
        } catch (Exception e) {
            throw new StreamLineException( "Cannot instantiate Transaction manager type:: " + transactionManagerType.getName() );
        }

        DataSourceXAConnectionFactory connectionFactory = new DataSourceXAConnectionFactory(
                tm, xds
        );

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                connectionFactory, connector, null, null, false, false
        );

        PoolingDataSource dataSource = new PoolingDataSource(connector);

        dataSource.setAccessToUnderlyingConnectionAllowed( true );

        dm.setDs( dataSource );

        return dataSource;
    }

}
